package controllers

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"smallstory/models"
	"time"
	"strconv"
	"smallstory/config"
)

var storyDao models.StoryDAO

type StoryController struct {
	mvc.C
}

type ApiResponse struct {
	Code         int         `json:"code"`
	ErrorMessage string      `json:"errorMessage"`
	PageTotal    int         `json:"pageTotal"`
	Data         interface{} `json:"data"`
}

func init() {
	storyDao = models.StoryDAO{}
}

func (c *StoryController) GetStoryList(ctx iris.Context) {

	var data interface{}

	lastID, err1 := ctx.URLParamInt("lastid")
	startID, _ := ctx.URLParamInt("startid")

	load, errLoad := ctx.URLParamBool("load")

	if errLoad != nil {
		ctx.JSON(ApiResponse{Code: 400, ErrorMessage: "缺少 load 必要参数"})
		return
	}

	if err1 == nil && load {
		data = ApiResponse{Code: config.SUCCESED, ErrorMessage: "成功", Data: storyDao.FindListLoadmore(lastID)}
	} else {
		data = ApiResponse{Code: config.SUCCESED, ErrorMessage: "成功", Data: storyDao.FindNewListByPage(startID)}
	}
	ctx.JSON(data)
}

func (c *StoryController) GetChapterDetails(ctx iris.Context) {

	sid, _ := ctx.URLParamInt("sid")
	id, _ := ctx.URLParamInt("id") //根据 id 分页
	pageSize, _ := ctx.URLParamInt("pagesize")

	chapters, total := storyDao.FindChapterListByID(sid, id, pageSize)
	data := ApiResponse{Code: config.SUCCESED, ErrorMessage: "成功", Data: chapters, PageTotal: total}
	ctx.JSON(data)
}

func (c *StoryController) CreateChapter(ctx iris.Context) {

	now := time.Now()
	uid := ctx.FormValue("uid")
	title := ctx.FormValue("title")
	key := ctx.FormValue("keyword")

	story := models.Story{}
	story.Tag = ctx.FormValue("tag")
	story.Title = title
	story.Createdate = now.Local().UnixNano() / 1e6

	chapter := models.Chapter{}
	chapter.Uid = uid
	chapter.Content = ctx.FormValue("content")
	chapter.Createdate = now.Local().UnixNano() / 1e6
	chapter.Key = key
	var data interface{}

	if storyDao.CreateByUid(uid, story, chapter) == 1 {
		data = ApiResponse{Code: config.SUCCESED, ErrorMessage: "提交成功"}
	} else {
		data = ApiResponse{Code: config.SUCCESED, ErrorMessage: "提交失败"}
	}

	ctx.JSON(data)
}

func (c *StoryController) AddChapter(ctx iris.Context) {

	now := time.Now()
	chapter := models.Chapter{}
	chapter.Uid = ctx.FormValue("uid")
	chapter.Content = ctx.FormValue("content")
	chapter.Createdate = now.Local().UnixNano() / 1e6
	chapter.Sid, _ = strconv.Atoi(ctx.FormValue("sid"))
	chapter.Key = ctx.FormValue("keyword")

	var data interface{}
	if storyDao.Add(chapter) == 1 {
		data = ApiResponse{Code: config.SUCCESED, ErrorMessage: "提交成功"}
	} else {
		data = ApiResponse{Code: config.SUCCESED, ErrorMessage: "提交失败"}
	}

	ctx.JSON(data)
}

func (c *StoryController) Like(ctx iris.Context) {

	chapter := models.Chapter{}
	chapter.Id, _ = strconv.Atoi(ctx.FormValue("cid"))
	chapter.Uid = ctx.FormValue("uid")

	data := ApiResponse{Code: storyDao.UpdateLikeCount(chapter)}

	ctx.JSON(data)
}
